#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include <cstring>
#include <string>

using namespace LogModule;
int main()
{
    int _sockfd = ::socket(AF_INET,SOCK_DGRAM,0);
    if(_sockfd<0)
    {
        LOG(ERROR)<<"创建套接字失败";
        return 1;
    }
    LOG(INFO)<<"创建套接字成功,socket is:"<<_sockfd;

    //填充网络信息
    struct sockaddr_in local;
    bzero(&local,sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = ::htons(8080);
    local.sin_addr.s_addr = INADDR_ANY;
    //设置信息
    int n = ::bind(_sockfd,(sockaddr*)&local,sizeof(local));
    if(n<0)
    {
        LOG(ERROR)<<"bind失败";
        return 2;
    }
    LOG(INFO)<<"bind成功";

    while(true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)&peer,&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::string echo_string = "sever# ";
            echo_string += buffer;
            LOG(INFO)<<"收到客户端消息:"<<echo_string;
            sendto(_sockfd,echo_string.c_str(),echo_string.size(),0,(sockaddr*)&peer,len);
        }
    }

    return 0;
}